/*  ----------------------------------------------------------------------------
 *  Arello Mobile
 *  Fast 3d Engine
 *  ----------------------------------------------------------------------------
 * Except where otherwise noted, this work is licensed under
 * http://creativecommons.org/licenses/by/3.0
 */

#include "../Thread.h"
#include <pthread.h>

namespace liba
{
namespace threads
{

class Thread::Impl
{
public:
	Impl()
		:	handle( 0 )
	{}
	pthread_t handle;
	// this function is to access protected thread->run()
	static void run(Thread * thread)
	{
		thread->run();
	}
};

Thread::Thread()
:	impl( new Impl() ),
	processID( 0 ),
	need_termination_flag( false )
{}

Thread::~Thread()
{
	if( impl->handle )
	{
		impl->handle = 0;
	}
	delete impl; impl = 0;
}

static void * ThreadProc(void * thread_pointer)
{
    Thread * thread = reinterpret_cast<Thread *>(thread_pointer);
	
	Thread::Impl::run( thread );
    return 0;
}

bool Thread::start()
{
	if( impl->handle ) 
		return false;

	bool ok = pthread_create( &impl->handle, 0, ThreadProc, this );
    
	return ok != 0;
}

void Thread::wait_termination()
{
	if( impl->handle )
	{
		void * result = 0;
		pthread_join( impl->handle, &result );
		impl->handle = 0;
	}
}

void Thread::request_termination()
{
	need_termination_flag = true;
}

bool Thread::need_termination()volatile const
{
	return need_termination_flag;
}

bool Thread::set_priority( int priority )
{
	return false;
}

void Thread::resume()
{
}

void Thread::suspend()
{
}

} // namespace threads
} //namespace liba